<template>
  <div ref="chartContainer" class="chart-container"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, nextTick } from 'vue'
import * as echarts from 'echarts/core'
import { LineChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  DataZoomComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'

echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  LineChart,
  CanvasRenderer,
  DataZoomComponent
])

const props = defineProps({
  chartData: {
    type: Object,
    required: true
  },
  timeRange: {
    type: String,
    default: 'month'
  }
})

const chartContainer = ref(null)
let chart: echarts.ECharts | null = null

const getXAxisData = () => {
  const range = props.timeRange
  if (range === 'week') {
    return ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
  } else if (range === 'month') {
    return ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
  } else if (range === 'quarter') {
    return ['Q1', 'Q2', 'Q3', 'Q4']
  } else {
    return ['2018', '2019', '2020', '2021', '2022', '2023', '2024']
  }
}

const getSeriesData = () => {
  if (props.timeRange === 'quarter') {
    return {
      income: [120000, 132000, 101000, 134000],
      expense: [90000, 98000, 87000, 96000]
    }
  } else if (props.timeRange === 'year') {
    return {
      income: [580000, 620000, 710000, 780000, 890000, 940000, 1080000],
      expense: [490000, 520000, 600000, 650000, 720000, 790000, 860000]
    }
  } else if (props.timeRange === 'week') {
    return {
      income: [9200, 10500, 11800, 8600, 7500, 5200, 4800],
      expense: [7600, 8200, 9500, 7100, 6400, 4200, 3900]
    }
  } else {
    return props.chartData
  }
}

const initChart = () => {
  if (!chartContainer.value) return
  
  const xAxisData = getXAxisData()
  const seriesData = getSeriesData()
  
  chart = echarts.init(chartContainer.value)
  const option = {
    title: {
      text: '收入支出趋势',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'normal'
      },
      show: false
    },
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(255, 255, 255, 0.9)',
      borderColor: '#e6e6e6',
      borderWidth: 1,
      textStyle: {
        color: '#333'
      },
      formatter: function(params: any) {
        let res = params[0].axisValue + '<br/>'
        params.forEach((item: any) => {
          res += `<div style="display:flex;align-items:center;margin:5px 0;">
                    <span style="display:inline-block;width:10px;height:10px;background:${item.color};border-radius:50%;margin-right:8px;"></span>
                    <span>${item.seriesName}: </span>
                    <span style="font-weight:bold;margin-left:5px">¥ ${item.value.toLocaleString()}</span>
                  </div>`
        })
        return res
      }
    },
    legend: {
      data: ['收入', '支出'],
      bottom: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      top: '8%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: xAxisData,
      axisLine: {
        lineStyle: {
          color: '#ddd'
        }
      },
      axisTick: {
        alignWithLabel: true
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        show: false
      },
      axisLabel: {
        formatter: (value: number) => {
          if (value >= 10000) {
            return (value / 10000) + 'w'
          }
          return value
        }
      },
      splitLine: {
        lineStyle: {
          color: '#eee',
          type: 'dashed'
        }
      }
    },
    series: [
      {
        name: '收入',
        type: 'line',
        data: seriesData.income,
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        lineStyle: {
          width: 3,
          color: '#409EFF'
        },
        itemStyle: {
          color: '#409EFF'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(64, 158, 255, 0.35)' },
              { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
            ]
          }
        }
      },
      {
        name: '支出',
        type: 'line',
        data: seriesData.expense,
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        lineStyle: {
          width: 3,
          color: '#F56C6C'
        },
        itemStyle: {
          color: '#F56C6C'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(245, 108, 108, 0.35)' },
              { offset: 1, color: 'rgba(245, 108, 108, 0.1)' }
            ]
          }
        }
      }
    ]
  }
  
  chart.setOption(option)
  
  window.addEventListener('resize', handleResize)
}

const handleResize = () => {
  chart && chart.resize()
}

const updateChart = () => {
  if (!chart) return
  
  const xAxisData = getXAxisData()
  const seriesData = getSeriesData()
  
  chart.setOption({
    xAxis: {
      data: xAxisData
    },
    series: [
      {
        name: '收入',
        data: seriesData.income
      },
      {
        name: '支出',
        data: seriesData.expense
      }
    ]
  })
}

watch(() => props.timeRange, () => {
  nextTick(updateChart)
})

watch(() => props.chartData, () => {
  nextTick(updateChart)
}, { deep: true })

onMounted(() => {
  nextTick(() => {
    initChart()
  })
})

// 组件销毁时清理chart
defineExpose({
  dispose: () => {
    if (chart) {
      chart.dispose()
      chart = null
    }
    window.removeEventListener('resize', handleResize)
  }
})
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 100%;
}
</style> 